<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Websocket客户端</title>
</head>
<body>
<form onsubmit="return false">
    <textarea name="message" style="width: 400px;height: 200px"></textarea>
    <input type="button" value="发送数据" onclick="send(this.form.message.value);">
    <h3>服务端输出</h3>
    <textarea id="responseText" style="width: 400px;height: 200px"></textarea>
    <input type="button" value="清空数据" onclick="javascript:document.getElementById('responseText').value=''">
</form>
<script>
    var socket;
    if (window.WebSocket) {
        socket = new WebSocket("ws://localhost:8899/ws");
        socket.onmessage = function onMessage(event) {
            var ta = document.getElementById("responseText");
            ta.value = ta.value + "\n" + event.data;
        };
        socket.onopen = function onOpen(event) {
            var ta = document.getElementById("responseText");
            ta.value = "连接开启";
        };
        socket.onclose = function onClose(event) {
            var ta = document.getElementById("responseText");
            ta.value = ta.value + "\n" + "连接关闭";
        }

    } else {
        alert("您的浏览器版本过低，请升级后重试")
    }
    function send(message) {
        if (!window.WebSocket) {
            return;
        }
        if (socket.readyState === WebSocket.OPEN) {
            socket.send(message)
        } else {
            alert("连接未开启");
        }
    }
</script>
</body>
</html>